package com.lengxf.design;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class LoadBalancer {

    //饿汉式单例模式创建 直接初始化
//    private final static LoadBalancer instance =  new LoadBalancer();

    private final List<String> serverList;

    private LoadBalancer() {
        serverList = new ArrayList<>();
    }

    public static LoadBalancer getLoadBalancer() {
        return InstanceHolder.instance;
    }

    private static final class InstanceHolder {
        //懒汉式单例模式 只有被调用的时候才会进行实例加载
        //双重锁 可以使用此方式进行实现
        private static final LoadBalancer instance = new LoadBalancer();
    }

    public void addServer(String server) {
        serverList.add(server);
    }


    public void removeServer(String server) {
        serverList.remove(server);
    }

    public String getServer() {
        Random random = new Random();
        int i = random.nextInt(serverList.size());
        return serverList.get(i);
    }


}
